package cn.lg.soar.system.monitor.controller;

import cn.lg.soar.common.model.HttpResult;
import cn.lg.soar.common.model.PageQuery;
import cn.lg.soar.common.model.PageResult;
import cn.lg.soar.common.util.AssertUtil;
import cn.lg.soar.core.annotations.constraints.Id;
import cn.lg.soar.database.query.QueryParams;
import cn.lg.soar.database.query.SqueryWapper;
import cn.lg.soar.mvc.annotations.DetailMapping;
import cn.lg.soar.mvc.annotations.QueryMapping;
import cn.lg.soar.mvc.annotations.RemoveMapping;
import cn.lg.soar.system.api.constant.ModuleConst;
import cn.lg.soar.system.monitor.entity.OperationLog;
import cn.lg.soar.system.monitor.service.OperationLogService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author luguoxiang
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@RefreshScope
@Api(tags = {"操作日志"})
@RestController
@RequestMapping(ModuleConst.MODULE_NAME + "/log")
public class OperationLogController {

    @Value("${lg.monitor.log.retention-days:30}")
    private Integer day;

    @Autowired
    private OperationLogService service;

    @QueryMapping
    public HttpResult<PageResult<OperationLog>> query(PageQuery pageQuery, QueryParams params){
        return HttpResult.data(
                new SqueryWapper<>(OperationLog.class).query(this.service, pageQuery, params)
        );
    }

    @RemoveMapping
    public HttpResult<Void> remove(@RequestBody List<Long> ids){
        LocalDateTime dateTime = LocalDateTime.now().minusDays(30);
        AssertUtil.isTrue(
                this.service.remove(
                        Wrappers.<OperationLog>lambdaUpdate()
                                .in(OperationLog::getId, ids)
                                .le(OperationLog::getDatetime, dateTime)
                )
                , "删除日志失败，只能删除超过{0}天的日志", day);
        return HttpResult.success();
    }

    @DetailMapping
    public HttpResult<OperationLog> detail(@Id Long id) {
        return HttpResult.data(this.service.getById(id));
    }

}
